/**
 * Xinfei.com Inc.
 * <p>
 * Copyright (c) 2004-2023 All Rights Reserved.
 */
package com.xinfei.techplayprod.biz.service.impl;

import com.xinfei.techplayprod.biz.model.enums.TechplayErrDtlEnum;
import com.xinfei.techplayprod.biz.model.exception.TechplayException;
import com.xinfei.techplayprod.biz.rr.dto.UserDto;
import com.xinfei.techplayprod.biz.service.UserService;
import com.xinfei.techplayprod.biz.util.LoggerUtil;
import com.xinfei.techplayprod.dal.entity.UserEntity;
import com.xinfei.techplayprod.dal.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 用户服务接口默认实现
 *
 * @author Chengsheng.Li
 * @version $ TeamServiceImpl, v 0.1 2023/8/29 09:02 Chengsheng.Li Exp $
 */
@Service
public class UserServiceImpl implements UserService {

    /**
     * BIZ-SERVICE
     */
    private static final Logger LOGGER = LoggerFactory.getLogger("BIZ-SERVICE");
    @Autowired
    UserMapper userMapper;
    private ExecutorService threadPoolExecutor = Executors.newSingleThreadExecutor();
    /**
     * 默认事务模版
     */
    @Autowired
    private TransactionTemplate transactionTemplate;

    /**
     * 构造用户实体
     *
     * @param userDto 用户DTO
     * @return 用户实体
     */
    private static UserEntity buildUserEntity(UserDto userDto) {

        UserEntity user = new UserEntity();

        user.setId(userDto.getId());
        user.setAge(userDto.getAge());
        user.setName(userDto.getName());
        user.setEmail(userDto.getEmail());

        return user;
    }

    @Override
    public void addOrEdit(UserDto userDto) {

        LoggerUtil.info(LOGGER, "收到用户新增或更新请求，userDto=", userDto);

        // 1 构造用户实体
        final UserEntity user = buildUserEntity(userDto);

        // 2 DB操作
        transactionTemplate.execute(new TransactionCallback() {
            @Override
            public Object doInTransaction(TransactionStatus status) {

                // 2.1 新增user
                if (user.getId() == null || user.getId() == 0) {
                    userMapper.insert(user);
                    userDto.setId(user.getId());
                }

                // 2.2 更新user
                else {
                    int count = userMapper.updateById(user);
                    if (count != 1) {
                        throw new TechplayException(TechplayErrDtlEnum.DATA_UPDATE_EXCEPTION, "更新用户异常，user=" + user);
                    }
                }

                return null;
            }
        });

        LoggerUtil.info(LOGGER, "用户新增或更新请求处理结束，userDto=", userDto);
    }

    @Override
    public long test(int t) {
        long start = System.currentTimeMillis();

        transactionTemplate.execute(new TransactionCallback() {
            @Override
            public Object doInTransaction(TransactionStatus status) {
                UserEntity user = userMapper.selectById(1);
                user.setAge(1);
                // 2.2 更新user
                userMapper.updateById(user);
                return null;
            }
        });
        return System.currentTimeMillis() - start;
    }

    /*
     * 用来做性能测试
     * */
    private int getCallerLine() {
        try {
            //使用StackTraceElement类获取堆栈信息
            StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[0];
            //返回所在行号
            return stackTraceElement.getLineNumber();
        } catch (Throwable e) {
            return 0;
        }
    }
}
